package org.wing.modules.product.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.wing.common.result.Result;
import org.wing.modules.product.entity.Product;
import org.wing.modules.product.service.IProductService;

@RestController
@RequestMapping("/api/product")
@AllArgsConstructor
public class ProductController {

    private final IProductService productService;

    /*
    * 创建商品
    * */
    @PostMapping
    public Result<String> createProduct(@RequestBody Product product) {
        boolean saved = productService.save(product);
        return saved ? Result.success("创建成功") : Result.failed("创建失败");
    }


    /*
     * 分页查询商品
     * */
    @GetMapping("/page")
    public Result<Page<Product>> getProducts(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) String productName) {

        Page<Product> page = new Page<>(current, size);
        Page<Product> productPage = productService.pageList(page, productName);
        return Result.success(productPage);
    }

    /**
     * 根据ID获取商品详情
     */
    @GetMapping("/{id}")
    public Result<Product> detail(@PathVariable Long id) {
        Product product = productService.getById(id);
        return product != null ? Result.success(product) : Result.failed("商品不存在");
    }

    /**
     * 更新商品信息
     */
    @PutMapping
    public Result<String> update(@RequestBody Product product) {
        boolean updated = productService.updateById(product);
        return updated ? Result.success("更新成功") : Result.failed("更新失败");
    }

    /**
     * 根据ID删除商品（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        boolean removed = productService.removeById(id);
        return removed ? Result.success("删除成功") : Result.failed("删除失败");
    }
}
